<template>
  <light-dialog
    class="light-dialog"
    :title="data.shipName || ' '"
    v-dialogDrag
    :visible.sync="dialogVisible"
    :width="400"
    :modal="false"
    :modal-append-to-body="false"
    :append-to-body="false"
    :close-on-click-modal="false"
    @close="close"
    hiddenButton
    isClose
    top="120px"
    left="20px"
  >
    <div class="right" slot="right">
      <div
        class="abnormal"
        v-if="data.mmsi === '412302820'"
        style="background-color: #d3d3d3"
      >
        离线中
      </div>
      <i class="el-icon-close" @click="close"></i>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick" class="ship-tab">
      <!-- 船舶信息 -->
      <el-tab-pane label="AIS信息" name="info">
        <div slot="label" class="tab-label">船舶信息</div>
        <div class="tab-content">
          <form-detail
            class="form-detail"
            :data="data"
            :option="option"
            labelWidth="75"
          ></form-detail>
          <el-image
            class="img"
            :src="data.picture"
            v-if="data.picture"
          ></el-image>
        </div>
      </el-tab-pane>
      <!-- 案件信息 -->
      <el-tab-pane label="当前案件" name="task">
        <div slot="label" class="tab-label">当前案件</div>
        <div class="tab-content">
          <form-detail
            v-if="activeName === 'task' && this.taskInfo.caseId"
            class="form-detail task-form"
            :data="taskInfo"
            :option="taskOptions"
            :dict="dictData"
            labelWidth="80"
            :colNum="1"
          ></form-detail>
          <div class="no-data" v-else>当前无案件</div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 按钮列表 -->
    <div class="bottom-content">
      <div class="button-list">
        <el-button class="ele-button" size="mini" @click="handleLocation(info)"
          >定位</el-button
        >
        <el-button class="ele-button" size="mini" @click="handleTrajectory"
          >轨迹</el-button
        >
        <el-button
          class="ele-button"
          size="mini"
          @click="handleWake"
          v-loading="waveLoading"
          :disabled="waveLoading"
          element-loading-spinner="el-icon-loading"
          >{{ `${buttonState.isWave ? "关闭" : ""}尾迹` }}</el-button
        >
        <!-- <el-button
          class="ele-button"
          size="mini"
          @click="handleShipLine"
          v-loading="lineLoading"
          :disabled="lineLoading"
          element-loading-spinner="el-icon-loading"
          >{{ `${buttonState.isLine ? "关闭" : ""}航线` }}</el-button
        > -->
        <!-- <el-button
          class="ele-button"
          size="mini"
          @click="handleTask"
          element-loading-spinner="el-icon-loading"
          >{{ `${buttonState.task ? "结束" : ""}案件` }}</el-button
        > -->
        <!-- <el-button class="ele-button" size="mini" @click="handleMessage()"
          >发送消息</el-button
        > -->
      </div>
      <!-- 轨迹查询 -->
      <div class="time-select" v-if="trajectorySelect">
        <div class="block">
          <el-date-picker
            size="small"
            v-model="trajectoryTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </div>
        <div class="time-select-button-list">
          <el-button
            class="first"
            size="small"
            @click="timeSelectSubmit()"
            v-loading="trajectoryLoading"
            :disabled="trajectoryLoading"
            element-loading-spinner="el-icon-loading"
            >查询</el-button
          >
          <el-button class="second" size="small" @click="handleDownload()"
            >导出</el-button
          >
          <el-button class="second" size="small" @click="timeSelectCancel()"
            >取消</el-button
          >
        </div>
      </div>
    </div>
    <!-- <task-dialog
      ref="task"
      @reloadTask="getTask(data.mmsi)"
      :alarmList="alarmList"
    ></task-dialog> -->
  </light-dialog>
</template>

<script>
import Overlay from "ol/Overlay";
// import TaskDialog from "./TaskDialog";
import { option, initButtonState, taskOptions } from "./options";
import { dateFormat } from "@/utils/date";
// import { getShipRoute } from "@/api/shipping/route";
const getShipRoute = () => {};
import { getAlarmShipByid } from "@/api/shipping/workCase";
import { getList as getAlarmList } from "@/api/shipping/area";
import { moveToCenterByLonAndLat } from "@/page/chart/js/util";
import { getPositionList } from "@/api/shipping/position";

import drawMethod from "@/page/chart/js/draw";

let wakeTimer = null;

export default {
  props: {
    info: {
      default: () => {},
    },
    map: {
      default: () => {},
    },
  },
  data() {
    return {
      activeName: "info",
      dialogVisible: false,
      option,
      buttonState: initButtonState(),
      trajectorySelect: false,
      trajectoryTime: "",
      shipAnchorData: {},
      waveLoading: false,
      lineLoading: false,
      trajectoryLoading: false,
      alarmList: [],
      taskInfo: {},
      taskOptions,
      dictData: {
        type: [
          {
            value: "1",
            label: "普通案件",
          },
          {
            value: "2",
            label: "特殊案件",
          },
        ],
        areaId: [],
      },
    };
  },
  computed: {
    isShipAnchor() {
      return !this.shipAnchorData.mmsi;
    },
    data: {
      get() {
        return this.info;
      },
      set() {},
    },
  },
  methods: {
    open(row = {}) {
      // 判断选中船舶是否发生变化
      if (row.mmsi !== this.data.mmsi) {
        this.buttonState = initButtonState();
        this.timeSelectCancel();
        this.clearWave();
        this.clearShipLine();
      }
      // 获取船舶案件
      this.getTask(row.shipId);
      this.data = { ...row };
      this.dialogVisible = true;
    },
    close() {
      this.dialogVisible = false;
      this.trajectorySelect = false;
      this.trajectoryTime = "";
      this.buttonState = initButtonState();
      clearInterval(wakeTimer);
      this.timeSelectCancel();
      this.clearWave();
      this.clearShipLine();
    },
    // 轨迹
    handleTrajectory() {
      this.trajectorySelect = true;
    },
    timeSelectSubmit() {
      if (!this.trajectoryTime || this.trajectoryTime.length < 2) return;
      // 停止海图跟踪功能
      this.$emit("update:isTracking", false);
      // 所有上层图层全部隐藏
      for (let layerTmp of this.map.getLayers().getArray()) {
        if (layerTmp.get("name") !== "MAIN") {
          layerTmp.setVisible(false);
        }
      }
      this.trajectoryLoading = true;
      getPositionList({
        shipId: this.data.shipId,
        beginTime: +new Date(this.trajectoryTime[0]),
        endTime: +new Date(this.trajectoryTime[1]),
      })
        .then(({ data }) => {
          this.trajectoryLoading = false;
          drawMethod.drawShipTrajectory(this.map, data, this.TrajectoryInfo);
        })
        .catch(() => {
          this.trajectoryLoading = false;
        });
    },
    timeSelectCancel() {
      this.trajectorySelect = false;
      for (let layerTmp of this.map.getLayers().getArray()) {
        if (layerTmp.get("name") === "TRAJECTORY") {
          this.map.removeLayer(layerTmp);
        } else {
          layerTmp.setVisible(true);
        }
      }
    },
    // 尾迹开关
    handleWake() {
      this.buttonState.isWave = !this.buttonState.isWave;
      if (this.buttonState.isWave) {
        if (wakeTimer) {
          clearInterval(wakeTimer);
        }
        this.waveLoading = true;
        this.getShipWake(this.data.shipId);
        wakeTimer = setInterval(() => {
          this.getShipWake(this.data.shipId);
        }, 10000);
      } else {
        this.clearWave();
      }
    },
    // 显示尾迹
    getShipWake(shipId) {
      const endTime = +new Date();
      const startTime = endTime - 30 * 60 * 1000;
      const row = {
        beginTime: startTime,
        endTime: endTime,
        shipId: shipId,
      };
      getPositionList(row)
        .then(({ data }) => {
          this.waveLoading = false;
          if (data && data.length > 0) {
            this.clearWave(false);
            drawMethod.drawShipWake(this.map, data);
          }
        })
        .catch(() => {
          this.waveLoading = false;
        });
    },
    // 清空尾迹
    clearWave(isClear = true) {
      if (isClear) clearInterval(wakeTimer);
      for (let layerTmp of this.map.getLayers().getArray()) {
        if (layerTmp.get("name") === "WAVE") {
          setTimeout(() => {
            this.map.removeLayer(layerTmp);
          });
        }
      }
    },
    // 航线开关
    handleShipLine() {
      this.buttonState.isLine = !this.buttonState.isLine;
      if (this.buttonState.isLine) {
        this.lineLoading = true;
        this.getShipLine(this.data.mmsi);
      } else {
        this.clearShipLine();
      }
    },
    // 显示航线
    async getShipLine(mmsi) {
      const { data } = await getShipRoute(mmsi);
      this.lineLoading = false;
      if (data) {
        this.clearShipLine();
        drawMethod.drawShipLine(this.map, data);
      }
    },
    // 展示轨迹航路点的信息
    TrajectoryInfo(evt) {
      if (evt.dragging) {
        return;
      }
      var pixel = this.map.getEventPixel(evt.originalEvent);
      var feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
        return feature;
      });
      const id = "TrajectoryInfo";
      if (feature && feature.values_.name) {
        let dom = document.getElementById(id);
        if (dom) return;
        const row = feature.values_.detail;
        var msg = document.createElement("div");
        msg.setAttribute("id", id);
        let msgSpeed = document.createElement("div");
        msgSpeed.innerHTML = `速度：${row.speed}节`;
        let msgHeading = document.createElement("div");
        msgHeading.innerHTML = `角度：${row.course}°`;
        let msgTime = document.createElement("div");
        msgTime.innerHTML = `时间：${dateFormat(new Date(row.receiveTime))}`;
        msg.appendChild(msgSpeed);
        msg.appendChild(msgHeading);
        msg.appendChild(msgTime);
        let msgTip = new Overlay({
          element: msg,
          offset: [15, 0],
          positioning: "center",
        });
        msgTip.setPosition(evt.coordinate);
        this.map.addOverlay(msgTip);
      } else {
        let dom = document.getElementById(id);
        if (dom) {
          dom.parentNode.removeChild(document.getElementById(id));
        }
      }
    },
    // 清空航线
    clearShipLine() {
      for (let layerTmp of this.map.getLayers().getArray()) {
        if (layerTmp.get("name") === "SHIPLINE") {
          setTimeout(() => {
            this.map.removeLayer(layerTmp);
          });
        }
      }
    },
    // 获取船舶案件
    getTask(id) {
      getAlarmShipByid(id).then(({ data }) => {
        this.taskInfo = data || {};
        // if (data && data.taskId) {
        //   this.buttonState.task = true;
        // } else {
        //   this.buttonState.task = false;
        // }
      });
    },
    // 案件
    handleTask() {
      if (this.buttonState.task) {
        // 关闭案件
        this.$refs.task.open(this.taskInfo);
      } else {
        this.$refs.task.open(this.data);
      }
    },
    handleClick(row) {
      console.log("name: ", row.name);
    },
    // 获取敏感区域
    async getAlarmList() {
      const { data } = await getAlarmList();
      this.alarmList = data;
      this.dictData.areaId = data;
    },
    // 轨迹导出
    handleDownload() {
      let url = "";
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "船舶轨迹.xls");
      document.body.appendChild(link);
      link.click();
    },
    // 定位
    handleLocation(row) {
      moveToCenterByLonAndLat([row.lon, row.lat], this.map);
    },
  },
  watch: {
    trajectorySelect(val) {
      if (val) {
        var now = +new Date();
        var before = now - 7 * 24 * 3600 * 1000;
        this.trajectoryTime = [
          dateFormat(new Date(before)),
          dateFormat(new Date()),
        ];
      }
    },
  },
  created() {
    this.getAlarmList();
  },
  destroyed() {
    this.close();
  },
};
</script>

<style lang="scss" scoped>
.light-dialog {
  &::v-deep .head {
    margin: -1px;
    background-color: $base-theme-sub-color;
    .title {
      color: #fff !important;
    }
    i {
      color: #fff;
    }
  }
  .right {
    .abnormal {
      font-size: 12px;
      color: #fff;
      display: inline-block;
      border-radius: 10px;
      padding: 0 8px;
      margin-right: 10px;
    }
    i {
      color: #fff;
      cursor: pointer;
      line-height: 23px;
    }
  }
}
.form-detail {
  &::v-deep .mnh-form-detail-item {
    font-size: 12px;
    margin-bottom: 5px;
  }
}
.tab-content {
  min-height: 190px;
  position: relative;
  .form-detail {
    &::v-deep .mnh-form-detail-item {
      font-size: 12px;
      margin-bottom: 5px;
    }
  }
  .img {
    width: 60px;
    height: 60px;
    position: absolute;
    top: 0px;
    right: 10px;
    z-index: 100;
  }
  .task-form {
    &::v-deep .mnh-form-detail-item {
      margin-bottom: 20px;
    }
  }
}
.bottom-content {
  margin-top: 10px;
  .button-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 10px;
    .ele-button {
      flex: 1;
      color: #fff;
      background-color: $base-theme-sub-color;
      padding: 7px 0;
      &::v-deep .el-loading-spinner {
        margin-top: 0;
        top: calc(50% - 6px);
      }
    }
  }
  .time-select {
    &::v-deep .el-date-editor {
      width: 100%;
    }
    .time-select-button-list {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      .first {
        color: #fff;
        width: 48%;
        background-color: $base-theme-sub-color;
      }
      .second {
        width: 48%;
        color: $base-theme-sub-color;
        border-color: $base-theme-sub-color;
      }
    }
  }
}
.img {
  width: 60px;
  height: 60px;
  position: absolute;
  top: 50px;
  right: 10px;
  z-index: 100;
}
</style>
